<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;
use app\admin\model\hospital\Hospital;

/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    
    
    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $column = [];
        $starttime = Date::unixtime('day', -6);
        $endtime = Date::unixtime('day', 0, 'end');
        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }
        $this->view->assign([
            'totaluser'         => User::where('role',10)->count('id'),
            'totaltodayuser'         => User::where('role',10)->whereTime('createtime','today')->count('id'),
            'totalyesterdayuser'         => User::where('role',10)->whereTime('createtime','yesterday')->count('id'),

            'totalsale'         => User::where('role',20)->count('id'),
            'totaltodaysale'         => User::where('role',20)->whereTime('createtime','today')->count('id'),
            'totalyesterdaysale'         => User::where('role',20)->whereTime('createtime','yesterday')->count('id'),

            'totaldoctor'         => User::where('role',30)->count('id'),
            'totaltodaydoctor'         => User::where('role',30)->whereTime('createtime','today')->count('id'),
            'totalyesterdaydoctor'         => User::where('role',30)->whereTime('createtime','yesterday')->count('id'),

            'totalhospital'         => Hospital::count('id'),
            'totaltodayhospital'         => Hospital::whereTime('createtime','today')->count('id'),
            'totalyesterdayhospital'         => Hospital::whereTime('createtime','yesterday')->count('id'),

            'totaladdon'        => $totaladdon,
            'totaladmin'        => Admin::count(),
            'totalcategory'     => \app\common\model\Category::count(),
            'todayusersignup'   => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin'    => User::whereTime('logintime', 'today')->count(),
            'sevendau'          => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau'         => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu'          => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu'          => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums'       => count($dbTableList),
            'dbsize'            => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums'    => Attachment::count(),
            'attachmentsize'    => Attachment::sum('filesize'),
            'picturenums'       => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize'       => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
        ]);

        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        return $this->view->fetch();
    }

    public function ordercount(){

        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);

        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $hospitalList = Db::name("hospital")->select();
        foreach($hospitalList as &$hospital){
            $data = Db::name("order")->where('createtime', 'between', [$starttime, $endtime])
                ->where('hospital_id',$hospital['id'])
                ->where('status','in',[10,20,30])
                ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
            $dateArr = [];
            $dateList = [];
            foreach($data as $item){
                $dateArr[$item['order_date']] = $item['nums'];
            }
            foreach($column as $key=>$date){
                $dateList[$key] = $dateArr[$date] ?? 0;
            }


            $hospital['data'] = $dateList;
        }
        return json([
            'column' => $column,
            'data' => $hospitalList,
        ]);
    }


    public function goodscount(){

        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);

        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $goodsList = Db::name("goods")->select();
        foreach($goodsList as &$goods){
            $data = Db::name("order_goods")->alias('order_goods')->join('order_master order','order.id = order_goods.order_master_id')->where('order.createtime', 'between', [$starttime, $endtime])
                ->where('order_goods.goods_id',$goods['id'])
                ->where('order.status','=','30')
                ->field('COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(order.createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
            $dateArr = [];
            $dateList = [];
            foreach($data as $item){
                $dateArr[$item['order_date']] = $item['nums'];
            }
            foreach($column as $key=>$date){
                $dateList[$key] = $dateArr[$date] ?? 0;
            }


            $goods['data'] = $dateList;
        }
        return json([
            'column' => $column,
            'data' => $goodsList,
        ]);
    }


    public function orderprice(){
        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);
        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $data = Db::name("order_master")->where('createtime', 'between', [$starttime, $endtime])
                ->where('pay_status','=',1)
                ->field('sum(price) AS totalprice, DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
        $dateArr = [];
        $dateList = [];
        foreach($data as $item){
            $dateArr[$item['order_date']] = (float)$item['totalprice'];
        }
        foreach($column as $key=>$date){
            $dateList[$key] = $dateArr[$date] ?? 0;
        }
        return json([
            'column' => $column,
            'data' => $dateList
        ]);
    }

    public function rechargeprice(){ 
        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);
        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $data = Db::name("recharge_package_order")->where('createtime', 'between', [$starttime, $endtime])
                ->where('status','=',1)
                ->field('sum(money) AS totalprice, DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
        $dateArr = [];
        $dateList = [];
        foreach($data as $item){
            $dateArr[$item['order_date']] = (float)$item['totalprice'];
        }
        foreach($column as $key=>$date){
            $dateList[$key] = $dateArr[$date] ?? 0;
        }
        return json([
            'column' => $column,
            'data' => $dateList
        ]);
    }


    public function messagecount(){
        
        $messageTypeList = Db::name("message_type")->select();
        $dataArr = [];
        $column =[];
        foreach($messageTypeList as &$message){
            $count = Db::name("message_board")
                ->where('message_type_id',$message['id'])
                ->count();
           $dataArr[] = $count;
           $column[] = $message['title'];
        }
        return json([
            'column' => $column,
            'data' => $dataArr,
        ]);
    }


    // 统计用户数量
    public function tableuser(){
        $limit = $this->request->request('limit');
        $offset = $this->request->request('offset');
        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-01 00:00:00'), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);
        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }

        $list = [];
        foreach($column as $key=>$date){
            $list[$key] = [
                'date' => $date,
                'count' => Db::name("user")->where('role',10)->where('createtime', 'between', [strtotime($date), strtotime($date.' 23:59:59')])->count(),
                'totalcount' => Db::name("user")->where('role',10)->where('createtime', '<=', strtotime($date.' 23:59:59'))->count(),
            ];
        }

        return json(array("total" => count($list), "rows" => $list));
        
    }

    /** 销售金额统计 */
    public function saleprice(){

        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);

        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $saleList = Db::name("user")->where('role',20)->select();
        foreach($saleList as &$sale){
            $data = Db::name("order_master")->where('createtime', 'between', [$starttime, $endtime])
                ->where('sole_id',$sale['id'])
                ->where('status','=','30')
                ->field('sum(price - refund_price) AS totalprice, DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
            $dateArr = [];
            $dateList = [];
            foreach($data as $item){
                $dateArr[$item['order_date']] = $item['totalprice'];
            }
            foreach($column as $key=>$date){
                $dateList[$key] = $dateArr[$date] ?? 0;
            }


            $sale['data'] = $dateList;
        }
        return json([
            'column' => $column,
            'data' => $saleList,
        ]);
    }

    /** 销售金额统计 */
    public function saleorder(){

        $between = $this->request->request('between');
        $between = $between ? explode(' - ', $between) : [date('Y-m-d 00:00:00',strtotime('-7day')), date('Y-m-d 23:59:59')];

        $starttime = strtotime($between[0]);
        $endtime = strtotime($between[1]);

        $column = [];
        for ($time = $starttime; $time <= $endtime;) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $saleList = Db::name("user")->where('role',20)->select();
        foreach($saleList as &$sale){
            $data = Db::name("order_master")->where('createtime', 'between', [$starttime, $endtime])
                ->where('sole_id',$sale['id'])
                ->where('status','=','30')
                ->field('count(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(createtime), "%Y-%m-%d") AS order_date')
                ->group('order_date')
                ->select();
            $dateArr = [];
            $dateList = [];
            foreach($data as $item){
                $dateArr[$item['order_date']] = $item['nums'];
            }
            foreach($column as $key=>$date){
                $dateList[$key] = $dateArr[$date] ?? 0;
            }


            $sale['data'] = $dateList;
        }
        return json([
            'column' => $column,
            'data' => $saleList,
        ]);
    }

}
